package com.groupbuying.currency.producer.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.groupbuying.currency.producer.connector.CustomerFeign;
import com.groupbuying.currency.producer.connector.SysconfigFeign;
import com.groupbuying.currency.producer.constants.*;
import com.groupbuying.currency.producer.dao.CurrencyCustomerDao;
import com.groupbuying.currency.producer.domain.CurrencyCustomerDO;
import com.groupbuying.currency.producer.domain.CurrencyCustomerLogDO;
import com.groupbuying.currency.producer.domain.CurrencyPrepayInfoDO;
import com.groupbuying.currency.producer.domain.CurrencyResultDO;
import com.groupbuying.currency.producer.mq.CurrencyMQConfig;
import com.groupbuying.currency.producer.service.*;
import com.groupbuying.currency.producer.utils.DateUtils;
import com.groupbuying.currency.producer.utils.JSONUtils;
import com.groupbuying.currency.producer.utils.MD5Utils;
import com.groupbuying.currency.producer.utils.RedisUtils;
import com.groupbuying.currency.producer.utils.currencyOperUtils.DateFormatHelper;
import com.groupbuying.currency.producer.utils.currencyOperUtils.SnowflakeIdWorker;
import com.groupbuying.currency.producer.utils.currencyOperUtils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auter miaozhenfei
 * @date 2019/8/14 18:12
 */
@Service
public class CurrencyOperServiceImpl implements CurrencyOperService {
    private static Logger log = LoggerFactory.getLogger(CurrencyOperServiceImpl.class);
    @Autowired
    private CurrencyCustomerLogService currencyCustomerLogService;
    @Autowired
    private CurrencyCustomerService currencyCustomerService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private CurrencyPrepayInfoService currencyPrepayInfoService;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private CurrencyResultService currencyResultService;

    @Autowired
    private CurrencyCustomerDao currencyCustomerDao;

    @Autowired
    private Producer producer;

    @Autowired
    private CustomerFeign customerFeign;


    /**
     * 根据订单号查询单条积分支付状态
     */
    @Override
    public String queryPayStateByOrderNum(Map mapParams) {
        // 解析map参数
        Object tempParam = mapParams.get("orderNum");
        String orderNum = tempParam == null ? null : tempParam.toString();


        Map returnMap = new HashMap();
        if (null == orderNum) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
            log.debug("=================查询积分支付状态订单号为空=========", returnMap);

            return JSONUtils.parseJSON(returnMap);
        }
        Map map = new HashMap();
        map.put("orderNum", orderNum);
        map.put("delFlag", "1");
        List<CurrencyPrepayInfoDO> list = currencyPrepayInfoService.list(map);
        log.debug("=================查询积分支付状态根据订单号查询结果为=========", list);
        return JSONUtils.beanToJson(list != null && list.size() > 0 ? list.get(0) : null);

    }

    /**
     * 密码校验
     *
     * @param
     * @param
     * @return
     */

    @Override
    public Map passWordCheck(Map mapParams) {

        // 解析map参数
        Object tempParam = mapParams.get("customerId");
        String customerId = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("passWord");
        String passWord = tempParam == null ? null : tempParam.toString();

        Map returnMap = new HashMap();
        if (null == customerId || null == passWord) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
            return returnMap;
        }
        CurrencyCustomerDO currencyCustomer = currencyCustomerService.get(customerId);
        if (null == currencyCustomer) {
            returnMap.put("return_code", ReturnCodeEnum.LOGINNAMENOTEXIT.getKey());
            returnMap.put("message", ReturnCodeEnum.LOGINNAMENOTEXIT.getValue());
            return returnMap;
        }
        //String customerId = FilterContextHandler.getUserID();
        String pw = MD5Utils.encrypt(customerId, passWord);
        String payPasswd = currencyCustomer.getPassword();
        if (!pw.equals(payPasswd)) {
            returnMap.put("return_code", ReturnCodeEnum.PAYMENTERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.PAYMENTERROR.getValue());
            return returnMap;
        }
        returnMap.put("return_code", ReturnCodeEnum.SUCCESS.getKey());
        returnMap.put("message", ReturnCodeEnum.SUCCESS.getValue());
        return returnMap;

    }

    /**
     * 生成预支付信息
     *
     * @param
     * @param
     * @return
     */

    @Override
    public Map creatPrePayInfo(Map mapParams) {

        // 解析map参数
        Object tempParam = mapParams.get("customerId");
        String customerId = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("orderNum");
        String orderNum = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("payCurrency");
        BigDecimal payCurrency = tempParam == null ? null : new BigDecimal(tempParam.toString());
        tempParam = mapParams.get("platformBusnum");
        String platformBusnum = tempParam == null ? null : tempParam.toString();
        Map returnMap = new HashMap();
        if (null == customerId || null == payCurrency || null == platformBusnum) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
            return returnMap;
        }
        String prePayNo = SnowflakeIdWorker.nextId();
        //String prePayCode = UuidUtils.createUuid();
        // 生成预支付信息
        CurrencyPrepayInfoDO prePayInfoDO = new CurrencyPrepayInfoDO();
        prePayInfoDO.setCustomerId(customerId);
        prePayInfoDO.setCreateTime(DateFormatHelper.getNowTimeStr());
        prePayInfoDO.setPayCurrency(payCurrency);
        prePayInfoDO.setPrepayNo(prePayNo);
        prePayInfoDO.setState(CurrencyPrepayInfoEnumConstants.ENUM_STATE_UNDERWAY);
        prePayInfoDO.setBusinessType(CurrencyPrepayInfoEnumConstants.ENUM_BUSINESSTYPE_CURRENCYPAY);
        prePayInfoDO.setPlatformBusnum(platformBusnum);
        prePayInfoDO.setOrderNum(orderNum);
        String str = JSONUtils.beanToJson(prePayInfoDO);
        redisUtils.setKey(prePayNo, str, 60 * 30L);
        returnMap.put("return_code", ReturnCodeEnum.SUCCESS.getKey());
        returnMap.put("message", ReturnCodeEnum.SUCCESS.getValue());
        returnMap.put("prePayInfoDO", prePayInfoDO);
        log.error("生成预支付信息成功" + str);
        return returnMap;
    }


    /**
     * 订单订单支付 直接核减不冻结
     * 积分支付，直接扣减
     * @param
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map subOrderCurrency(Map mapParams) {

        // 解析map参数
        Object tempParam = mapParams.get("prePayNo");
        String prePayNo = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("passWord");
        String passWord = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("payId");
        String payId = tempParam == null ? null : tempParam.toString();


        Map returnMap = new HashMap();
        if (null == prePayNo || null == passWord) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
            return returnMap;
        }

        if (null == redisUtils.getValue(prePayNo)) {
            returnMap.put("return_code", ReturnCodeEnum.FIAL.getKey());
            returnMap.put("message", ReturnCodeEnum.FIAL.getValue());
            log.debug("========支付单号过期prePayNo：" + prePayNo);
            return returnMap;
        }

        String prePayInfoStr = (String) redisUtils.getValue(prePayNo);
        CurrencyPrepayInfoDO prePayInfo = JSON.parseObject(prePayInfoStr, CurrencyPrepayInfoDO.class);

        //CurrencyPrepayInfoDO prePayInfo = (CurrencyPrepayInfoDO) JSONUtils.jsonToBean(prePayInfoStr, CurrencyPrepayInfoDO.class);
        String customerId = prePayInfo.getCustomerId();
        BigDecimal payCurrency = prePayInfo.getPayCurrency();
        String platformBusnum = prePayInfo.getPlatformBusnum();
        String orderNum = prePayInfo.getOrderNum();
        //防止二次提交
        String idempotent = "currency_sub" + prePayNo;

        //从redis取
        Object str = redisUtils.getValue(idempotent);

        if (str != null && !StringUtils.isEmpty(str.toString())) {
            //redis中有说明上一次订单重复
            returnMap.put("return_code", ReturnCodeEnum.ORDERSREPEAT.getKey());
            returnMap.put("message", ReturnCodeEnum.ORDERSREPEAT.getValue());
            Map map = new HashMap();
            map.put("currencyCode", ReturnCodeEnum.ORDERSREPEAT.getKey());
            map.put("message", ReturnCodeEnum.ORDERSREPEAT.getValue());
            map.put("prePayNo", prePayNo);
            map.put("payCurrency", payCurrency);
            map.put("customerId", customerId);
            map.put("platformBusnum", platformBusnum);
            map.put("orderNum", prePayInfo.getOrderNum());
            Message message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_TO_FINANCIAL, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            log.debug("============================消息发送到ES成功=========" + message);
            return returnMap;
        } else {
            //将当前时间戳放到redis中 预防二次注册
            String currentTimeMillis = System.currentTimeMillis() + "";
            redisUtils.setKey(idempotent, currentTimeMillis, 60 * 60 * 2L);
        }



        //todo 幂等从数据库中查询支付单号是否已支付过

        CurrencyPrepayInfoDO currencyPrepayInfo = currencyPrepayInfoService.queryPayStateByOrderNum(orderNum);
        if (null != currencyPrepayInfo) {
            returnMap.put("return_code", ReturnCodeEnum.ORDERSREPEAT.getKey());
            returnMap.put("message", ReturnCodeEnum.ORDERSREPEAT.getValue());
            log.debug("==========积分支付重复提交订单：=========" + orderNum, returnMap);
            return returnMap;

        }

        String redisLockKey = "subMoney" + customerId;
        String timeStamp = "" + System.currentTimeMillis();

        /**
         * 分布式锁
         */
        try {
            while (!redisUtils.setIfAbsent(redisLockKey, timeStamp, 3L)) {
                Thread.sleep(100L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>");
        CurrencyCustomerDO currencyCustomer = currencyCustomerService.get(customerId);
        if (null == currencyCustomer) {
            //保存错误支付信息
            prePayInfo.setState(CurrencyPrepayInfoEnumConstants.ENUM_STATE_FAIL);
            prePayInfo.setCreateTime(DateFormatHelper.getNowTimeStr());
            prePayInfo.setPrepayId(UuidUtils.createUuid());
            prePayInfo.setDelFlag("1");
            prePayInfo.setBusinessType(prePayInfo.getPlatformBusnum() + "平台" + "支付积分账户不存在");
            currencyPrepayInfoService.save(prePayInfo);

            log.debug("==========支付余额账户不存在=========" + customerId, returnMap);
            Map map = new HashMap();
            map.put("currencyCode", ReturnCodeEnum.CUSTOMERNOERROR.getKey());
            map.put("message", ReturnCodeEnum.CUSTOMERNOERROR.getValue());
            map.put("prePayNo", prePayNo);
            map.put("payCurrency", payCurrency);
            map.put("customerId", customerId);
            map.put("platformBusnum", platformBusnum);
            map.put("orderNum", prePayInfo.getOrderNum());
            Message message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_TO_FINANCIAL, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            log.debug("============================消息发送到ES成功=========" + message);
            returnMap.put("return_code", ReturnCodeEnum.CUSTOMERNOERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.CUSTOMERNOERROR.getValue());
            return returnMap;
        }
        //密码校验
        String pw = MD5Utils.encrypt(customerId, passWord);
        String payPasswd = currencyCustomer.getPassword();
        if (!pw.equals(payPasswd)) {

            prePayInfo.setState(CurrencyPrepayInfoEnumConstants.ENUM_STATE_FAIL);
            prePayInfo.setCreateTime(DateFormatHelper.getNowTimeStr());
            prePayInfo.setPrepayId(UuidUtils.createUuid());
            prePayInfo.setDelFlag("1");
            prePayInfo.setBusinessType(prePayInfo.getPlatformBusnum() + "平台" + "支付密码不正确");
            currencyPrepayInfoService.save(prePayInfo);


            log.debug("==========支付密码不正确支付单号prePayNo=========" + prePayNo, returnMap);
            Map map = new HashMap();
            map.put("currencyCode", ReturnCodeEnum.PAYPWDERROR.getKey());
            map.put("message", ReturnCodeEnum.PAYPWDERROR.getValue());
            map.put("prePayNo", prePayNo);
            map.put("payCurrency", payCurrency);
            map.put("customerId", customerId);
            map.put("platformBusnum", platformBusnum);
            map.put("orderNum", prePayInfo.getOrderNum());
            Message message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_TO_FINANCIAL, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            log.debug("============================消息发送到ES成功=========" + message);
            returnMap.put("return_code", ReturnCodeEnum.PAYPWDERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.PAYPWDERROR.getValue());
            return returnMap;
        }

        BigDecimal oldCurrency = currencyCustomer.getUseCurrency();
        System.err.println("oldCurrency:" + oldCurrency);


        //如果小于o余额不足
        if (oldCurrency.compareTo(payCurrency) < 0) {


            prePayInfo.setState(CurrencyPrepayInfoEnumConstants.ENUM_STATE_FAIL);
            prePayInfo.setCreateTime(DateFormatHelper.getNowTimeStr());
            prePayInfo.setPrepayId(UuidUtils.createUuid());
            prePayInfo.setDelFlag("1");
            prePayInfo.setBusinessType(prePayInfo.getPlatformBusnum() + "平台" + "支付订单积分不足");
            currencyPrepayInfoService.save(prePayInfo);
            log.debug("============================支付订单积分不足=========" + customerId, returnMap);
            Map map = new HashMap();
            map.put("currencyCode", ReturnCodeEnum.ACCOUNTLACK.getKey());
            map.put("message", ReturnCodeEnum.ACCOUNTLACK.getValue());
            map.put("prePayNo", prePayNo);
            map.put("payCurrency", payCurrency);
            map.put("customerId", customerId);
            map.put("platformBusnum", platformBusnum);
            map.put("orderNum",orderNum);
            //用于支付成功异步通知的MQ消息发送
            Message message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_TO_FINANCIAL, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            log.debug("=================发送mq===================" + message);
            returnMap.put("return_code", ReturnCodeEnum.ACCOUNTLACK.getKey());
            returnMap.put("message", ReturnCodeEnum.ACCOUNTLACK.getValue());
            return returnMap;
        }

        //账户余额减少
        BigDecimal newCurrency = oldCurrency.subtract(payCurrency);
        System.err.println("newCurrency+" + newCurrency);

        currencyCustomer.setUseCurrency(newCurrency);
        currencyCustomer.setTotalCurrency(currencyCustomer.getUseCurrency().add(currencyCustomer.getFreezeCurrency()));

        //   直接更新积分表
        currencyCustomerService.update(currencyCustomer);
        //预支付订单改成支付订单存到数据库
        prePayInfo.setState(CurrencyPrepayInfoEnumConstants.ENUMSTATE_SUCCESS);
        prePayInfo.setOpeTime(DateFormatHelper.getNowTimeStr());
        prePayInfo.setPrepayId(UuidUtils.createUuid());
        prePayInfo.setDelFlag("1");
        prePayInfo.setBusinessType(prePayInfo.getBusinessType() + "成功");
        currencyPrepayInfoService.save(prePayInfo);

        try {

            //拼装日志明细
            CurrencyCustomerLogDO currencyCustomerLog = new CurrencyCustomerLogDO();
            currencyCustomerLog.setActivityId(null);
            currencyCustomerLog.setLogId(sysconfigFeign.createLogID());
            currencyCustomerLog.setCustomerId(customerId);
            currencyCustomerLog.setPayId(payId);
            currencyCustomerLog.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);

            currencyCustomerLog.setCreateTime(DateUtils.format(new Date(), DateUtils.YMDHMS));
            currencyCustomerLog.setCurrencySource(CurrencyConstants.CURRENCY_SOURCE_CONSUME);
            currencyCustomerLog.setCurrencyType(CurrencyConstants.CURRENCY_TYPE_DECREASE);
            currencyCustomerLog.setCurrencyCount(payCurrency);
            currencyCustomerLog.setCurrencyBalance(currencyCustomer.getTotalCurrency());
            currencyCustomerLogService.save(currencyCustomerLog);
            //保存直接核减余额的记录表
            currencyResultService.saveCurrencyResult(currencyCustomerLog, prePayInfo);
            log.debug("===============拼装日志明细成功customerId=========" + customerId);

            //发送短信
            String msg = "积分消费成功，扣除" + payCurrency + "积分。";
            customerFeign.sendSmsWithCustomerId(customerId,msg);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("========================拼装日志明细失败customerid=========" + customerId + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            returnMap.put("return_code", ReturnCodeEnum.FIAL.getKey());
            returnMap.put("message", ReturnCodeEnum.FIAL.getValue());
            return returnMap;
        } finally {
            Object redisLockValue = redisUtils.getValue(redisLockKey);
            if (redisLockValue != null && timeStamp.equals(redisLockValue.toString())) {
                redisUtils.delKey(redisLockKey);
            }
        }
        Map map = new HashMap();
        map.put("currencyCode", ReturnCodeEnum.SUCCESS.getKey());
        map.put("message", ReturnCodeEnum.SUCCESS.getValue());
        map.put("prePayNo", prePayNo);
        map.put("payCurrency", payCurrency);
        map.put("customerId", customerId);
        map.put("platformBusnum", platformBusnum);
        map.put("orderNum", orderNum);
        map.put("payId", payId);
        Message message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_TO_FINANCIAL, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
        producer.send(message);
        //用于支付成功积分变动提心的MQ消息发送
        message = new Message(CurrencyMQConfig.TOPIC, CurrencyMQConfig.TAG_PAY_FOR_SENDMESSAGE, JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).getBytes());
        producer.send(message);
        log.info("============================消息发送到消费者中心成功customer=========" + message);

        returnMap.put("return_code", ReturnCodeEnum.SUCCESS.getKey());
        returnMap.put("message", ReturnCodeEnum.SUCCESS.getValue());
        return returnMap;
    }


    /**
     * 积分支付退款接口 直接核减不冻结
     *
     * @return subFrozenBalance
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map addOrderCurrency(Map mapParams) {

        // 解析map参数
        Object tempParam = mapParams.get("prePayNo");
        String orderNum = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("customerId");
        String customerId = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("payId");
        String payId = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("backCurrency");
        BigDecimal backCurrency = tempParam == null ? null : new BigDecimal(tempParam.toString());


        Map returnMap = new HashMap();
        if (null == customerId || null == backCurrency || null == orderNum || null == payId) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
            return returnMap;
        }
        //防止二次提交
        String idempotent = "currency_add" + orderNum;

        //从redis取
        Object str = redisUtils.getValue(idempotent);

        if (str != null && !StringUtils.isEmpty(str.toString())) {
            //redis中有说明上一次订单重复

            returnMap.put("return_code", ReturnCodeEnum.ORDERSREPEAT.getKey());
            returnMap.put("message", ReturnCodeEnum.ORDERSREPEAT.getValue());
            return returnMap;
        } else {
            //将当前时间戳放到redis中 预防二次
            String currentTimeMillis = System.currentTimeMillis() + "";
            redisUtils.setKey(idempotent, currentTimeMillis, 60 * 60 * 12L);
        }

        String redisLockKey = "addMoney" + customerId;
        String timeStamp = "" + System.currentTimeMillis();
        /**
         * 分布式锁
         */
        try {
            while (!redisUtils.setIfAbsent(redisLockKey, timeStamp, 3L)) {
                Thread.sleep(100L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //todo 幂等从数据库中查询支付单号是否已支付过

        CurrencyPrepayInfoDO currencyPrepayInfo = currencyPrepayInfoService.queryPayStateByOrderNum(orderNum);
        if (null == currencyPrepayInfo) {
            returnMap.put("return_code", ReturnCodeEnum.PARAMERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.PARAMERROR.getValue());
            log.debug("==========返还积分支付单号不正确orderNum：=========" + orderNum, returnMap);
            return returnMap;

        }
        //校验输入金额是否正确
        BigDecimal returnCurrency = currencyPrepayInfo.getPayCurrency();
        if (backCurrency.compareTo(returnCurrency) != 0) {
            returnMap.put("return_code", ReturnCodeEnum.VALIDATEACCOUNTERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.VALIDATEACCOUNTERROR.getValue());
            return returnMap;
        }
        if (!CurrencyResultEnumConstants.ENUM_STATE_SUCCESS.equals(currencyPrepayInfo.getState())) {
            returnMap.put("return_code", ReturnCodeEnum.REFUNDFAILURE.getKey());
            returnMap.put("message", ReturnCodeEnum.REFUNDFAILURE.getValue());
            log.debug("==========返还积分支付状态不正确orderNum：=========" + orderNum, returnMap);
            return returnMap;
        }


        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>");
        CurrencyCustomerDO currencyCustomer = currencyCustomerService.get(customerId);
        System.err.println(currencyCustomer);
        if (null == currencyCustomer) {
            returnMap.put("return_code", ReturnCodeEnum.CUSTOMERNOERROR.getKey());
            returnMap.put("message", ReturnCodeEnum.CUSTOMERNOERROR.getValue());
            log.debug("==========返还积分账户不存在=========" + customerId, returnMap);

            return returnMap;
        }

        BigDecimal oldCurrency = currencyCustomer.getUseCurrency();
        System.err.println("oldCurrency:" + oldCurrency);

        //账户余额增加
        BigDecimal newCurrency = oldCurrency.add(backCurrency);
        System.err.println("newCurrency+" + newCurrency);
        currencyCustomer.setUseCurrency(newCurrency);
        currencyCustomer.setTotalCurrency(currencyCustomer.getUseCurrency().add(currencyCustomer.getFreezeCurrency()));
        currencyCustomerService.update(currencyCustomer);

        try {

            //拼装日志明细
            CurrencyCustomerLogDO currencyCustomerLog = new CurrencyCustomerLogDO();
            currencyCustomerLog.setActivityId(null);
            currencyCustomerLog.setLogId(sysconfigFeign.createLogID());
            currencyCustomerLog.setCustomerId(customerId);
            currencyCustomerLog.setPayId(payId);
            currencyCustomerLog.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
            currencyCustomerLog.setCreateTime(DateUtils.format(new Date(), DateUtils.YMDHMS));
            currencyCustomerLog.setCurrencySource(CurrencyConstants.CURRENCY_SOURCE_CUREFOUND);
            currencyCustomerLog.setCurrencyType(CurrencyConstants.CURRENCY_TYPE_INCREASE);
            currencyCustomerLog.setCurrencyCount(backCurrency);
            currencyCustomerLog.setCurrencyBalance(currencyCustomer.getTotalCurrency());
            currencyCustomerLogService.save(currencyCustomerLog);
            log.debug("===============拼装日志明细成功customerId=========" + customerId);
            //保存直接核减余额的记录表
            currencyResultService.updateCurrencyResult(currencyPrepayInfo.getPrepayNo());
            currencyPrepayInfoService.updatePrepayInfo(currencyPrepayInfo);
            log.debug("===============拼装日志明细成功customerId=========" + customerId);


            //发送短信提示
            String msg = "您的积分支付订单退款成功，增加" + backCurrency + "积分。";
            customerFeign.sendSmsWithCustomerId(customerId,msg);


        } catch (Exception e) {

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            log.debug("========================拼装日志明细失败customerid=========" + customerId + e.getMessage());
            returnMap.put("return_code", ReturnCodeEnum.FIAL.getKey());
            returnMap.put("message", ReturnCodeEnum.FIAL.getValue());
            return returnMap;
        } finally {
            Object redisLockValue = redisUtils.getValue(redisLockKey);
            if (redisLockValue != null && timeStamp.equals(redisLockValue.toString())) {
                redisUtils.delKey(redisLockKey);
            }
        }
        returnMap.put("return_code", ReturnCodeEnum.SUCCESS.getKey());
        returnMap.put("message", ReturnCodeEnum.SUCCESS.getValue());


        return returnMap;
    }
}

//    /**
//     * 统计所有所有用户支付成功,失败、交易中的总金额
//     * queryAllCustomerBalance
//     */
//    public String queryAllPayMoney(Map mapParams) {
//
//        // 解析map参数
//        Object tempParam = mapParams.get("state");
//        String state = tempParam == null ? null : tempParam.toString();
//        tempParam = mapParams.get("startTime");
//        String startTime = tempParam == null ? null : tempParam.toString();
//        tempParam = mapParams.get("endTime");
//        String endTime = tempParam == null ? null : tempParam.toString();
//
//        Map returnMap = new HashMap();
//        if (null == state) {
//            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
//            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
//            log.debug("=================统计所有所有用户支付成功,失败、交易中的总金额状态码state参数为空=========", returnMap);
//
//            return JsonUtils.parseJSON(returnMap);
//        }
//        Map map = new HashMap();
//        map.put("state", state);
//        map.put("startTime", startTime);
//        map.put("endTime", endTime);
//        int totalMoney = customerBalanceResultDao.queryAllPayMoney(map);
//        returnMap.put("totalMoney", totalMoney);
//
//
//        return JsonUtils.parseJSON(returnMap);
//    }
//
//    /**
//     * 查询多条余额支付状态
//     *
//     * @param
//     * @param
//     * @return
//     */
//
//    public String queryAllBalanceResult(Map mapParams) {
//        // 解析map参数
//        Object tempParam = mapParams.get("customerUuid");
//        String customerUuid = tempParam == null ? null : tempParam.toString();
//        tempParam = mapParams.get("startTime");
//        String startTime = tempParam == null ? null : tempParam.toString();
//        tempParam = mapParams.get("endTime");
//        String endTime = tempParam == null ? null : tempParam.toString();
//        Map returnMap = new HashMap();
//        if (null == customerUuid) {
//            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
//            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
//            log.debug("=================查询多条余额支付状态参数customerUuid为空=========", returnMap);
//
//            return JsonUtils.parseJSON(returnMap);
//        }
//        Map map = new HashMap();
//        map.put("customerUuid", customerUuid);
//        map.put("startTime", startTime);
//        map.put("endTime", endTime);
//        List<CustomerBalanceResultDO> list = customerBalanceResultService.list(map);
//        if (list == null) {
//            returnMap.put("return_code", ReturnCodeEnum.CONTENTISEMPTY.getKey());
//            returnMap.put("message", ReturnCodeEnum.CONTENTISEMPTY.getValue());
//            log.debug("=================查询多条余额支付状态无记录=========", returnMap);
//
//            return JsonUtils.parseJSON(returnMap);
//        }
//
//        return JSON.toJSONString(list);
//
//    }
//    /**
//     * 查询余额支付状态
//     *
//     * @param
//     * @param
//     * @return
//     */
//    @Override
//    public String queryBalanceResult(Map mapParams) {
//        // 解析map参数
//        Object tempParam = mapParams.get("prePayNo");
//        String prePayNo = tempParam == null ? null : tempParam.toString();
////        tempParam = mapParams.get("customerUuid");
////        String customerUuid = tempParam == null ? null : tempParam.toString();
//
//        Map returnMap = new HashMap();
//        if (null == prePayNo) {
//            returnMap.put("return_code", ReturnCodeEnum.PARAMNULL.getKey());
//            returnMap.put("message", ReturnCodeEnum.PARAMNULL.getValue());
//            log.debug("=================查询余额支付状态订单号为空=========", returnMap);
//
//            return JsonUtils.parseJSON(returnMap);
//        }
//        Map map = new HashMap();
//        //map.put("customerUuid", customerUuid);
//        map.put("prePayNo", prePayNo);
//        map.put("is_delete", "1");
//        List<CustomerBalanceResultDO> list = customerBalanceResultService.list(map);
//        return JsonUtils.objectToJson(list != null && list.size() > 0 ? list.get(0) : null);
//
//
//    }
//
//



